﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;
using System.IO;
using Fatec.ControleEstoque.Attributes.Templates;

namespace Fatec.ControleEstoque.Interface
{

    public partial class ParentFormView_EditField : FieldTemplateUserControl
    {
        protected MetaTable parentTable;
        protected MetaTable childTable;

        public Boolean EnableDelete { get; set; }
        //public Boolean EnableInsert { get; set; }
        public Boolean EnableUpdate { get; set; }

        public String[] DisplayColumns { get; set; }

        public ParentFormView_EditField()
        {
            // set default values
            EnableDelete = true;
            EnableUpdate = true;
            //EnableInsert = false;
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            var attribute = Column.Attributes.OfType<ShowColumnsAttribute>().SingleOrDefault();

            if (attribute != null)
            {
                if (!attribute.EnableDelete)
                    EnableDelete = false;
                if (!attribute.EnableUpdate)
                    EnableUpdate = false;
                //if (!attribute.EnableInsert)
                //    EnableInsert = false;
            }

            var metaForeignKeyColumn = Column as MetaForeignKeyColumn;

            if (metaForeignKeyColumn != null)
            {
                // load Field Template
                String ddFolderVirtualPath = metaForeignKeyColumn.ParentTable.Model.DynamicDataFolderVirtualPath;
                String tableName = metaForeignKeyColumn.ParentTable.Name;

                String itemTemplate = ddFolderVirtualPath + "Templates/" + tableName + "Item.ascx";
                String editItemTemplate = ddFolderVirtualPath + "Templates/" + tableName + "Edit.ascx";
                //String insertItemTemplate = ddFolderVirtualPath + "Templates/" + tableName + "Insert.ascx";
                String footerTemplate = ddFolderVirtualPath + "Templates/" + tableName + "Footer.ascx";
                String headerTemplate = ddFolderVirtualPath + "Templates/" + tableName + "Header.ascx";
                String pagerTemplate = ddFolderVirtualPath + "Templates/" + tableName + "Pager.ascx";

                if (File.Exists(Server.MapPath(itemTemplate)))
                {
                    FormView1.ItemTemplate = LoadTemplate(itemTemplate);

                    // load any other field templates
                    //TODO: if an operation is required but no template throw error
                    if (File.Exists(Server.MapPath(editItemTemplate)))
                        FormView1.EditItemTemplate = LoadTemplate(editItemTemplate);

                    // because this is a parent no insert will be available
                    //if (File.Exists(Server.MapPath(insertItemTemplate))) 
                    //    FormView1.InsertItemTemplate = LoadTemplate(insertItemTemplate);

                    if (File.Exists(Server.MapPath(footerTemplate)))
                        FormView1.FooterTemplate = LoadTemplate(footerTemplate);
                    if (File.Exists(Server.MapPath(headerTemplate)))
                        FormView1.HeaderTemplate = LoadTemplate(headerTemplate);
                    if (File.Exists(Server.MapPath(pagerTemplate)))
                        FormView1.PagerTemplate = LoadTemplate(pagerTemplate);

                    // setup data source
                    FormDataSource.ContextTypeName = metaForeignKeyColumn.ParentTable.DataContextType.FullName;
                    FormDataSource.TableName = metaForeignKeyColumn.ParentTable.Name;

                    // enable update, delete and insert
                    FormDataSource.EnableDelete = EnableDelete;
                    // because this is a parent no insert will be available
                    FormDataSource.EnableInsert = false;
                    FormDataSource.EnableUpdate = EnableUpdate;

                    // get an instance of the MetaTable
                    parentTable = FormDataSource.GetTable();

                    // setup the GridView's DataKeys
                    String[] keys = new String[metaForeignKeyColumn.ParentTable.PrimaryKeyColumns.Count];
                    int i = 0;
                    foreach (var keyColumn in metaForeignKeyColumn.ParentTable.PrimaryKeyColumns)
                    {
                        keys[i] = keyColumn.Name;
                        i++;
                    }
                    FormView1.DataKeyNames = keys;

                    // enable AutoGenerateWhereClause so that the WHERE 
                    // clause is generated from the parameters collection
                    FormDataSource.AutoGenerateWhereClause = true;

                    // doing the work of this above because we can't
                    // set the DynamicDataManager table or where values
                    //DynamicDataManager1.RegisterControl(FormView1, false);
                }
                else
                {
                    throw new InvalidOperationException("ParentFormView_Edit requires an item template.");
                }
            }
            else
            {
                // throw an error if set on column other than MetaChildrenColumns
                throw new InvalidOperationException("The GridView FieldTemplate can only be used with MetaChildrenColumns");
            }
        }

        protected override void OnDataBinding(EventArgs e)
        {
            var metaForeignKeyColumn = Column as MetaForeignKeyColumn;

            // get the association attributes associated with MetaChildrenColumns
            var association = metaForeignKeyColumn.Attributes.
                OfType<System.Data.Linq.Mapping.AssociationAttribute>().FirstOrDefault();

            if (metaForeignKeyColumn != null && association != null)
            {
                // get keys ThisKey and OtherKey into Pairs
                var keys = new Dictionary<String, String>();
                var seperator = new char[] { ',' };
                var thisKeys = association.ThisKey.Split(seperator);
                var otherKeys = association.OtherKey.Split(seperator);
                for (int i = 0; i < thisKeys.Length; i++)
                {
                    keys.Add(thisKeys[i], otherKeys[i]);
                }

                // setup the where clause 
                // support composite foreign keys
                foreach (String fkName in metaForeignKeyColumn.ForeignKeyNames)
                {
                    // get the current fk column
                    var fkColumn = metaForeignKeyColumn.Table.GetColumn(fkName);
                    var pkColumn = metaForeignKeyColumn.ParentTable.GetColumn(keys[fkName]);

                    // setup parameter
                    var param = new Parameter();
                    param.Name = pkColumn.Name;
                    param.Type = pkColumn.TypeCode;

                    // get the value for this FK column
                    param.DefaultValue = GetColumnValue(fkColumn).ToString();

                    // add the where clause
                    FormDataSource.WhereParameters.Add(param);
                }
            }

            base.OnDataBinding(e);
        }
    }
}